console.log('load cbioportal (CGDS) interoperability tool');
// CGDS: MSKCC's Cancer Genomic Data Server 
// API: http://www.cbioportal.org/public-portal/web_api.jsp

CGDS={

	url:"https://script.google.com/macros/s/AKfycbwsJ5_WKUUZX1ccf7m1zYbtksCm-FEck_uC2agZv_DXAzsS7H4p/exec?",

	callbacks:{},

	uid:function(prefix){
		if(!prefix){prefix='UID'}
		var uid=prefix+Math.random().toString().slice(2);
		return uid
	},

	load:function(url,cb,er){ // load script / JSON
		var s = document.createElement('script');
		s.src=url;
		s.id = this.uid();
		if(!!cb){s.onload=cb}
		if(!!er){s.onerror=er}
		document.head.appendChild(s);
		setTimeout('document.head.removeChild(document.getElementById("'+s.id+'"));',10000); // is the waiting still needed ?
		return s.id
	},

	get:function(url,cb,id){
		if(!cb){cb=function(x){console.log(x)}};
		if(!id){id = this.uid('cb')};
		url+='&callback=CGDS.callbacks.'+id;
		this.callbacks[id]=cb;
		this.load(url);
		console.log(url);
	},

	call2cell:function(c){ // converts text from url calls into a dt table format
		var y = this.trailBlanks(c);
		return y.map(function(ci){return ci.split('\t')})
	},

	cell2dataset:function(x){
		var s = jmat.size(x);
		var n = s[0],m,y={};
		if(s.length>1){m=s[1]}
		else{m=1}
		var h = x[0] ; // field names
	    h = h.map(function(hi){return hi.replace(/\s/g,'_')});
		for(var j=0;j<m;j++){
			y[h[j]]=[];
			for(var i=1;i<n;i++){
				y[h[j]][i-1]=x[i][j];
			}
		}
		return y
	},

	call2dataset:function(x){
		return this.cell2dataset(this.call2cell(x));
	},

	trailBlanks:function(x){ // remove trailing blank if it exists
		var n = x.length;
		if(x[n-1].length==0){
			return this.trailBlanks(x.slice(0,n-1)); // recurse it untill no training blanks
		} else{
			return x;
		}
	},

	UI:function(){},

	// CGDS commands

	getTypesOfCancer:function(cb){ // returns list with cancer_study_id
		// example: 
		// CGDS.getTypesOfCancer(function(x){y = CGDS.call2dataset(x);console.log(y)})
		var url=this.url+'cmd=getTypesOfCancer';
		var id = this.uid('cb');this.get(url,cb,id);
		return id;
	},

	getGeneticProfiles:function(cancer_study_id,cb){ // Get All Genetic Profiles for a Specific Cancer Study
		// example
		// CGDS.getGeneticProfiles("gbm",function(x){y = CGDS.call2dataset(x);console.log(y)})
		var url=this.url+'cmd=getGeneticProfiles&cancer_study_id='+cancer_study_id+'_tcga';
		var id = this.uid('cb');this.get(url,cb,id);
		return id;
	},

	getCaseLists:function(cancer_study_id,cb){ // Get All Case Lists for a Specific Cancer Study
		// example:
		// CGDS.getCaseLists("gbm",function(x){y = x;console.log(y)})
		var url=this.url+'cmd=getCaseLists&cancer_study_id='+cancer_study_id+'_tcga';
		var id = this.uid('cb');this.get(url,cb,id);
		return id;
	},



}


// make sure jmat is there
if(!window.jmat){
	CGDS.load('https://jmat.googlecode.com/git/jmat.js')
}

x=7;
